package web;

import org.apache.log4j.BasicConfigurator;
import org.apache.log4j.Logger;

import human.User;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
import java.util.Arrays;
import java.util.Iterator;
import java.util.Map;

import jdbc.UserDao;

public class ServletElective extends javax.servlet.http.HttpServlet {
	public static final String SESS_AUTH = "auth";

	private static final Logger log = Logger.getLogger(ServletElective.class.getName());

	@Override
	public void init(ServletConfig config) throws ServletException {
		super.init(config);
		BasicConfigurator.configure();

		log.info("init() complete");
	}

	@Override
	public void destroy() {
		super.destroy();
		log.info("destroy() complete");
	}

	@Override
	protected synchronized void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException,
			IOException {
		if (req.getSession(true).getLastAccessedTime() < System.currentTimeMillis() - (long) (1000 * 60 * 20)) {
			req.getSession(true).removeAttribute(SESS_AUTH);
			req.getSession(true).invalidate();
			renderRedirectWithMessage(resp, "login.html", "Logged Out!");
		} else {

		}
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		if (req.getRequestURI().equals("/login.do")) {
			final String username = req.getParameter("username");
			final String password = req.getParameter("password");

			final String redirectUrl;
			final String message;

			if (username != null && username.length() > 0 && username.equalsIgnoreCase(password)) {
				req.getSession(true).setAttribute(SESS_AUTH, Boolean.TRUE);
				message = "Authorized!";
				redirectUrl = "ElectiveStart.html";
			} else {
				message = "Not Authorized!";
				redirectUrl = "login.jspx";
			}

			renderRedirectWithMessage(resp, redirectUrl, message);

		} else

		if (req.getRequestURI().equals("/testPOST.do")) {

			// See how to use session here
			final HttpSession session = req.getSession(true);
			final Integer reqcount = (Integer) session.getAttribute("req_count");
			if (reqcount == null) {
				session.setAttribute("req_count", 1);
			} else {
				session.setAttribute("req_count", reqcount + 1);
			}
			// end of session code

			// req.setCharacterEncoding("UTF-8");
			resp.setContentType("text/html; charset=UTF-8");

			// final Map params = req.getParameterMap();

			String email = req.getParameter("email").trim();
			String password = req.getParameter("password");
			String name = req.getParameter("name");
			String birthDate = req.getParameter("birthDate");
			String cardCode = req.getParameter("cardCode");
			String degree = req.getParameter("degree");

			System.out.println(email + password + name + birthDate.toString() + cardCode + degree);
			UserDao userDao = new UserDao();

			try {

				userDao.start();

				User user = new User();
				Long l = null;

				if (birthDate.matches("[A-Za-z0-9@.%+\\-#%]+")) {
					user.setBirthDate(Long.parseLong(birthDate));
				}
				if (email
				// .matches("^[A-Za-z0-9.%+\\-]+@[A-Za-z0-9.\\-]+\\.[A-Za-z]{2,4}"))
				// {
						.matches("[A-Za-z0-9@.%+\\-#%]+")) {
					user.setEmail(email);
				}
				if (password.matches("[A-Za-z0-9@#$%]+")) {
					user.setPassword(password);
				}
				user.setName(name);
				user.setCardCode(cardCode);
				user.setDegree(degree);

				userDao.insertUser(user);

				req.setCharacterEncoding("UTF-8");

				User userToPrint = userDao.selectUserByEmail(email);
				if (userToPrint != null) {
					req.setAttribute("stud", userToPrint.toString());

				} else {
					req.setAttribute("stud", "Selected null object.");
				}
				getServletContext().getRequestDispatcher("/ElectiveFirstJsp.jsp").forward(req, resp);

			} catch (SQLException e) {
				resp.sendError(503, e.getMessage());
				e.printStackTrace();
			} finally {
				userDao.close();
			}
		} else {

			final PrintWriter w = resp.getWriter();
			w.write("<html><body>");
			w.write("request URL: " + req.getRequestURL() + "<br/>");
			w.write("request URI: " + req.getRequestURI() + "<br/>");
			w.write("request QS: " + req.getQueryString() + "<br/>");
			w.write("request CP: " + req.getContextPath() + "<br/>");
			final Map params = req.getParameterMap();
			w.write("param count: " + params.keySet().size() + "<br/>");
			for (Iterator paramNameIt = params.keySet().iterator(); paramNameIt.hasNext();) {
				String paramName = (String) paramNameIt.next();
				w.write(paramName + "=>" + Arrays.toString(req.getParameterValues(paramName)) + "<br/>");
			}
			w.write("</body></html>");
		}
	}

	protected void renderRedirectWithMessage(HttpServletResponse resp, String redirectUrl, String message)
			throws IOException {
		final PrintWriter w = resp.getWriter();
		w.print("<html>");
		w.print("<head><META HTTP-EQUIV=Refresh CONTENT=\"2; URL=" + redirectUrl + "\"/></head>");
		w.print("<body style=\"text-align: center\">" + message + "</body>");
		w.print("</html>");
	}
}